package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.ILoginInfoCacheService;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequiredBlackList;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CheckBlackListInterceptor extends HandlerInterceptorAdapter {
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private ILoginInfoCacheService loginInfoCacheService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从redis中获取用户登录信息
        if (handler instanceof HandlerMethod) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(Consts.USER_INFO_TOKEN)) {
                        String token = cookie.getValue();
                        String stringInfo = loginInfoCacheService.getLoginInfo(token);
                        UserInfo userInfo = JSON.parseObject(stringInfo, UserInfo.class);
                        //判断请求是否贴有黑名单注解
                        HandlerMethod method = (HandlerMethod) handler;
                        if (method.hasMethodAnnotation(RequiredBlackList.class)) {
                            //获取请求中的将要访问用户id
                            String sId = request.getParameter("hisId");
                            long id = Long.parseLong(sId);
                            //查询将要访问用户的黑名单
                            List<UserInfo> blackList = userInfoService.getBlackList(id);
                            for (UserInfo user : blackList) {
                                if (user.getId() == userInfo.getId()) {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                }
            }
            return true;
        }
        return true;
    }
}
